<template>
  <div class="identify-main" :style="cssVars" v-if="JSON.stringify(tableData) !== '{}'">
    <div class="init-data">
      <p class="identify-module">原始数据</p>
      <div class="tabs-box">
        <ul class="search-list">
          <li class="search-item"
            v-if="identifyData[key]"
            v-for="(item, key) in finNameList"
            :class="{ 'active': curfinType === key }"
            :key="key"
            @click="clickFinType(key)">
            {{item}}
          </li>
        </ul>
        <div class="identify-switch" @click="showPicList=!showPicList">{{showPicList?'平衡试算':'原图'}}<i class="icon-switch"></i></div>
      </div>
      <div class="image-list" v-show="showPicList">
        <div v-for="(item, index) in base64List" :key="index">
          <el-image
              style="width: 43%; height: 240px"
              :src="item"
              :preview-src-list="[item]">
          </el-image>
          <p class="number">{{index+1}}</p>
        </div>
      </div>
      <ul class="formula-list" v-show="!showPicList">
        <li class="formula-item" v-for="(item, index) in formulaList" :key="index">
          <p class="formula-index"><span class="num">{{index+1}}</span>公式</p>
          <p class="formula-content">
            <span class="highlit"
              :class="{ 'on': currClickParentKey === subItem }"
              v-for="(subItem, subIndex) in item.itemList"
              :key="subIndex"
              @click="clickFinDetail(subItem, accountList[subItem])">
              {{accountList[subItem]?accountList[subItem]:subItem}}
            </span>
          </p>
          <div class="formula-detail">
            <p class="formula-module-title">{{tableData.headers[1]}}</p>
            <p class="formula-calc">
              <span class="highlit"
                :class="{ 'on': currClickParentKey === subItem }"
                v-for="(subItem, subIndex) in item.itemList"
                :key="subIndex"
                @click="clickFinDetailNum(subItem, '_1')">
                {{finDetailNum(subItem, '_1')}}
              </span>
            </p>
            <p class="formula-error"><span class="formula-tip">[误差]</span><span class="error">{{calFormula(item, '_1')}}</span></p>
            <p class="formula-result">
              <span class="formula-tip">[试算结果]</span>
              <span class="result" v-if="calFormula(item, '_1')==0">正确</span>
              <span class="result error" v-else>错误</span>
            </p>
          </div>
          <div class="formula-detail">
            <p class="formula-module-title">{{tableData.headers[2]}}</p>
            <p class="formula-calc">
              <span class="highlit"
                :class="{ 'on': currClickParentKey === subItem }"
                v-for="(subItem, subIndex) in item.itemList"
                :key="subIndex"
                @click="clickFinDetailNum(subItem, '_2')">
                {{finDetailNum(subItem, '_2')}}
              </span>
            </p>
            <p class="formula-error"><span class="formula-tip">[误差]</span><span class="error">{{calFormula(item, '_2')}}</span></p>
            <p class="formula-result">
              <span class="formula-tip">[试算结果]</span>
              <span class="result" v-if="calFormula(item, '_2')==0">正确</span>
              <span class="result error" v-else>错误</span>
            </p>
          </div>
        </li>
      </ul>
    </div>
    <!-- 识别数据 -->
    <div class="identify-data">
      <p class="identify-module">识别数据</p>
      <div class="identify-data-header">
        <div class="title">{{listType}}</div>
        <el-button @click="submitData" type="primary">完成并保存</el-button>
      </div>

      <div class="table-list">
        <div class="table-title">
          <div class="table-operation">
          </div>
          <div class="table-title-item" v-for="(item, index) in tableData.headers" :key="index">
            <span>{{item}}</span>
            <el-popover
              placement="top-start"
              width="287"
              trigger="hover" v-if="index===0">
              <div class="">
                <div><i class="icon el-icon-circle-check"></i><span class="popover-text">科目完全匹配</span></div>
                <div><i class="icon el-icon-warning-outline"></i><span class="popover-text">科目匹配置信度较低，建议检查是否匹配正确</span></div>
                <div><i class="icon el-icon-circle-close"></i><span class="popover-text">科目未匹配，显示原文识别内容</span></div>
              </div>
              <el-button class="tips-button" slot="reference"><i class="icon icon-tips"></i></el-button>
            </el-popover>
          </div>
        </div>
        <div class="table-data" v-for="(item, index) in tableData.dataList" :key="index">
          <div class="table-operation">
            <el-popover
                placement="left"
                popper-class="block-btn-wrap"
                width="150"
                trigger="click">
              <el-button type="link" @click="addBeforeRow(index)">向上增加一行</el-button>
              <br>
              <el-button type="link" @click="addAfterRow(index)">向下增加一行</el-button>
              <br>
              <el-button type="link" style="width: 100%;" @click="deleteRow(index)">删除整行</el-button>
              <i slot="reference"><i class="el-icon-s-tools"></i></i>
            </el-popover>

          </div>
          <div class="table-data-item">
            <el-select v-if="currClickKey == item.subject.id+''" v-model="inputVal" filterable placeholder="请选择" @change="handleNameInput(index)">
              <el-option
                v-for="(v, k) in accountOptions"
                :key="k"
                :label="v"
                :value="k">
              </el-option>
            </el-select>
            <span class="table-text" v-else @click="editTableMolecule(item.subject.id+'', item.subject.name)">{{item.subject.name}}</span>

            <i class="icon el-icon-circle-check" v-if="item.subject.similarity=='1'"></i>
            <i class="icon el-icon-circle-close" v-else-if="item.subject.similarity=='0'"></i>
            <i class="icon el-icon-warning-outline" v-else></i>
          </div>
          <div class="table-data-item">
            <el-input v-if="currClickKey == (item.subject.id+'_1')" v-model="inputVal" @change="handleVerifyInput(index, item.subject.id+'_1')">{{fidValuesVerify(item.values, item.subject.id+'_1')['verifyStr'] || '-'}}</el-input>
            <span class="table-text" v-else @click="editTableMolecule(item.subject.id+'_1', fidValuesVerify(item.values, item.subject.id+'_1')['verify'], item.subject.id+'')">{{ fidValuesVerify(item.values, item.subject.id+'_1')['verifyStr'] || '-'}}</span>
          </div>
          <div class="table-data-item">
            <el-input v-if="currClickKey == (item.subject.id+'_2')" v-model="inputVal" @change="handleVerifyInput(index, item.subject.id+'_2')">{{fidValuesVerify(item.values, item.subject.id+'_2')['verifyStr'] || '-'}}</el-input>
            <span class="table-text" v-else @click="editTableMolecule(item.subject.id+'_2', fidValuesVerify(item.values, item.subject.id+'_2')['verify'], item.subject.id+'')">{{fidValuesVerify(item.values, item.subject.id+'_2')['verifyStr'] || '-'}}</span>
          </div>
          <!-- fix：循环对象不定时的会出现不按key的顺序取值 所以暂时用上面每个key值列出来 -->
<!--          <div class="table-data-item" v-for="(subitem, subkey, subindex) in item.values" :key="subindex">-->
<!--            <el-input v-if="currClickKey == subkey" v-model="inputVal" @change="handleVerifyInput(key, subkey)">{{subitem.verifyStr || '-'}}</el-input>-->
<!--            <span class="table-text" v-else @click="editTableMolecule(subkey, subitem.verify, key)">{{subitem.verifyStr || '-'}}</span>-->
<!--          </div>-->
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    props: {
      themeColor: String,
      invoke: Function,
      editData: Object,
      identifyDataBack: Object,
    },
    computed: {
      cssVars() {
        return {
          "--themeColor": this.themeColor
        }
      },
    },
    watch: {
      editData(val) {
        if (val.standardId && val.textinTaskId) {
          this.getEditData()
        }
      },
      /* identifyData(val) {
        if (JSON.stringify(val) !== '{}') {
          this.curfinType = val.tab_income ? 'tab_income' : val.tab_balance ? 'tab_balance' : 'tab_cash'
          this.clickFinType(this.curfinType)
        } else {
          this.restData()
        }
      }, */
      /* 有时监听不到变化，用identifyDataBack中间值转一道 */
      identifyDataBack(val) {
        if (JSON.stringify(val) !== '{}') {
          this.identifyData = val
          this.curfinType = val.tab_income ? 'tab_income' : val.tab_balance ? 'tab_balance' : 'tab_cash'
          this.clickFinType(this.curfinType)
        } else {
          this.restData()
        }
      },
      editDialogVisible(val) {
        if (this.editData && this.editData.textinTaskId && this.editData.standardId) {
          this.getEditData()
        }
      },
      deep: true,
      immediate: true
    },
    data() {
      return {
        showPicList: false,
        curfinType: '',
        listType: '',
        tableData: {},   // 识别数据
        base64List: [],  // 图片列表
        accountList: {}, // 科目列表
        accountOptions: {}, //科目选项
        formulaList: {}, // 公式列表
        currClickKey: '',// 当前选中的单元格（根据key标识）
        currClickParentKey: '',// 当前选中的单元格的父节点
        inputVal: '',
        identifyData: {},
        finTypeList: {
          tab_balance: 'balance',
          tab_income: 'profit',
          tab_cash: 'cash'
        },
        finNameList: {
          tab_balance: '资产负债表',
          tab_income: '利润表',
          tab_cash: '现金流量表'
        },
      }
    },
    mounted() {
      if (this.editData && this.editData.textinTaskId && this.editData.standardId) {
        this.getEditData()
      }
    },
    methods: {
      getDataListItem(firstOptionsValue) {
        return {
          subject: {
            id: firstOptionsValue,
            name: this.accountList[firstOptionsValue],
            ocr: '',
            similarity: '',
          },
          values: [
            {
              id: firstOptionsValue+'_1',
              ocr: '',
              ocrStr: '',
              verify: '',
              verifyStr: '',
            },{
              id: firstOptionsValue+'_2',
              ocr: '',
              ocrStr: '',
              verify: '',
              verifyStr: '',
            }
          ]
        }
      },
      //向上增加一行
      addBeforeRow(index) {
        let firstOptionsValue = Object.keys(this.accountOptions)[0];
        this.inputVal = firstOptionsValue;
        this.tableData.dataList.splice(index, 0, this.getDataListItem(firstOptionsValue));
        this.currClickKey = firstOptionsValue;
      },
      //向下增加一行
      addAfterRow(index) {
        let firstOptionsValue = Object.keys(this.accountOptions)[0];
        this.inputVal = firstOptionsValue;
        this.tableData.dataList.splice(index+1, 0, this.getDataListItem(firstOptionsValue));
        this.currClickKey = firstOptionsValue;
      },
      //删除整行
      deleteRow(index) {
        let firstOptionsValue = Object.keys(this.accountOptions)[0];
        this.inputVal = firstOptionsValue;
        this.tableData.dataList.splice(index, 1);
        this.filterOptions();
      },
      // 获取编辑数据
      getEditData() {
        let params = {
          "textinTaskId": this.editData.textinTaskId,//财报ID
          "standardId": this.editData.standardId,     //财报准则ID
          "number": this.editData.number     //新增参数，列表中传来的number
        }
        this.invoke('finance_event_task_edit', params)
      },
      // 点击财务类型
      clickFinType(code) {
        console.log(code)
        // 后端数据结构有变动，前端定义好的值都放在了一个对象里面返回，所以分别赋值
        this.curfinType = code
        this.listType = this.finNameList[code]
        this.tableData = this.identifyData[code]
        
        let list = []
        this.identifyData[code].base64List.forEach(item => {
          list.push('data:image/*;base64,' + item)
        })
        this.base64List = list
        // this.base64List = this.identifyData[code].base64List

        this.accountList = this.identifyData.standardDetailVO[this.finTypeList[code]].subMap
        this.formulaList = this.identifyData.standardDetailVO[this.finTypeList[code]].formulaList
        this.filterOptions()
      },

      //科目选项排除已经选中的
      filterOptions(excludeId) {
        //已经选中的集合
        let ids = this.identifyData[this.curfinType]['dataList'].map((item)=>{
          return item.subject.id+''
        })
        //所有数据集合
        let subMap = JSON.parse(JSON.stringify(this.accountList))
        for(let key in subMap) {
          if(ids.includes(key)) {
            if(excludeId) {
              if(key !== excludeId) {
                delete subMap[key+'']
              }
            }else {
              delete subMap[key+'']
            }
          }
        }
        this.accountOptions = subMap
      },
      // 完成并保存
      submitData() {
        let params = this.identifyData
        let addNumber = this.identifyData.number || ''
        delete params.reason
        delete params.status
        delete params.standardDetailVO
        delete params.number

        for (const key in params) {
          if (
            params[key].base64List
          ) {
            delete params[key].headers
            delete params[key].base64List
          }
        }
        console.log({data: params, "number": this.editData.number || addNumber })
        this.invoke('finance_event_task_save', {data: params, number: this.editData.number || addNumber })
        // this.identifyData = {};
        // this.tableData = {};
      },
      fidValuesVerify(valuesArr, key) {
        let result = valuesArr.filter(item=>item.id === key);
        if(result.length > 0) {
          return result[0]
        }else {
          return ''
        }
      },
      // 编辑单元格
      editTableMolecule(key, val, parentKey) {
        this.currClickKey = key
        this.inputVal = val
        this.currClickParentKey = (parentKey ? parentKey : key)
        this.filterOptions(key)
      },
      // name input值改变
      handleNameInput(index) {
        this.identifyData[this.curfinType]['dataList'][index].subject.id = this.inputVal
        this.identifyData[this.curfinType]['dataList'][index].subject.name = this.accountList[this.inputVal]
        this.filterOptions();
        // console.log(this.identifyData[this.curfinType].dataMap)
      },
      // verify input值改变
      handleVerifyInput(index, subkey) {
        this.identifyData[this.curfinType]['dataList'][index].values.forEach((item, i)=> {
          if(item.id === subkey) {
            this.identifyData[this.curfinType]['dataList'][index].values[i].verify = this.inputVal
            this.identifyData[this.curfinType]['dataList'][index].values[i].verifyStr = this.numberFormat(this.inputVal)
          }
        })
      },
      // 点击左侧公式详情
      clickFinDetail(key, val) {
        if(!val) return;
        this.inputVal = val
        this.currClickParentKey = this.currClickKey = key
      },
      // 左侧公式详情的金额
      finDetailNum(id, flag) {
        if (this.tableData.dataList && this.tableData.dataList.filter(item=>item.subject.id+'' === id).length>0) {
            let objValue = this.tableData.dataList.filter(item=>item.subject.id+'' === id)[0]['values']
            let targetValueVerifyStr = objValue.filter(item=>item.id === id+flag)[0]
            return targetValueVerifyStr && targetValueVerifyStr['verifyStr'] || 0
        } else {
          if (['+', '-', '*', '/', '='].includes(id)) {
            return id
          } else {
            return 0
          }
        }
      },
      // 点击左侧金额
      clickFinDetailNum(id, flag) {
        if (this.tableData.dataList && this.tableData.dataList.filter(item=>item.subject.id+'' === id).length>0) {
            let objValue = this.tableData.dataList.filter(item=>item.subject.id+'' === id)[0]['values']
            let targetValueVerifyStr = objValue.filter(item=>item.id === id+flag)[0]
          this.currClickParentKey = id
          this.currClickKey = id+flag
          this.inputVal = targetValueVerifyStr && targetValueVerifyStr['verify'] || 0
          return this.inputVal
        } else {
          if (['+', '-', '*', '/', '='].includes(id)) {
            return id
          } else {
            return 0
          }
        }
      },
      calData(id, flag) {
        if (this.tableData.dataList && this.tableData.dataList.filter(item=>item.subject.id+'' === id).length>0) {
            let objValue = this.tableData.dataList.filter(item=>item.subject.id+'' === id)[0]['values']
            let targetValueVerifyStr = objValue.filter(item=>item.id === id+flag)[0]
          return targetValueVerifyStr && targetValueVerifyStr['verify'] || 0
        } else {
          return 0
        }
      },
      // 计算公式误差
      calFormula(val, flag) {
        let left = val.left.split(',')
        let leftNum = parseFloat(this.calData(left[0], flag))
        // console.log('leftNum', leftNum)

        let right = val.right.split(',')
        // let right = ['50','-','5','-','3','+','1']
        let rightNum = 0
        let symbolFlag = '+'
        
        right.forEach(item => {
          if (!['+', '-', '*', '/', '='].includes(item)) {
            if (symbolFlag==='+') {
              rightNum = rightNum + parseFloat(this.calData(item, flag))
            }
            if (symbolFlag==='-') {
              rightNum = rightNum - parseFloat(this.calData(item, flag))
            }
          } else {
            symbolFlag = item
          }
        })
        // console.log('rightNum', rightNum)
        return leftNum - rightNum
      },
      restData() {
        // 数据都重置
        this.showPicList = false
        this.curfinType = this.listType = this.currClickKey = this.currClickParentKey = this.inputVal = ''
        this.tableData = this.accountList = this.base64List = []
        this.formulaList = {}
      },
      // 千分位格式化
      numberFormat(val, type) {
        let source = val
        if (
          (!source && Number(source) !== 0) ||
          source === null ||
          source === undefined ||
          source === '' ||
          typeof source === 'object'
        ) {
          return '-'
        } else {
          source = Number(source.toString().match(/^-?\d+(?:\.\d{0,2})?/))
        }
        source = String(source)
        const isPositive = !/^-/.test(source)
        source = source.replace(/^-/, '')
        const reg = /\d{1,3}(?=(\d{3})+$)/g
        let ret = source.replace(/^(\d+)((\.\d+)?)$/, function (s, s1, s2) {
          return s1.replace(reg, '$&,') + s2
        })
        // ret = (isPositive ? '' : '') + ret
        const nums = ret.split('.')

        if (
          nums.length === 1 &&
          typeof Number(nums[0]) === 'number' &&
          type === 'AMOUNT'
        ) {
          ret = ret + '.00'
        } else if (
          ret.indexOf('.') !== -1 &&
          nums.length === 2 &&
          nums[1].length === 1
        ) {
          ret = ret + '0'
        }
        return isPositive ? ret : `(${ret})`
      }
    }
  }

</script>

<style  lang="less"  scoped>
.identify-main {
  display: flex;
}
.init-data {
  width: 30%;
  padding: 20px 35px;
  height: 100%;
}
.el-icon-circle-close {
  color: #FB2323;
}
.el-icon-warning-outline {
  color: #FF991C;
}
.el-icon-circle-check {
  color: #1BA854;
}
.popover-text {
  font-size: 12px;
  line-height: 18px;
  color: #999999;
  margin-left: 5px;
}
.identify-data {
  width: 70%;
  padding: 20px 35px;
  height: 100%;
  // border-left: 1px solid #E5E5E5;
  .subject {
    min-width: 265px;
    display: inline-block;
  }
  .icon {
    font-size: 14px;
  }
  .icon-tips {
    width: 15px;
    height: 15px;
    display: inline-block;
    background: url(../assets/icon-tips.png);
  }
  .tips-button {
    width: 15px;
    height: 15px;
    padding: 0;
    border: none;
    vertical-align: text-bottom;
    border-radius: 50%;
  }
}
.identify-data-header {
  display: flex;
  justify-content: space-between;
  padding-bottom: 27px;
  .title {
    font-size: 16px;
    color: var(--themeColor);
  }
  .el-button {
    background: var(--themeColor);
    border-color: var(--themeColor);
    width: 76px;
    height: 28px;
    line-height: 28px;
    font-size: 12px;
    padding: 0;
  }
}

.table-list {
  width: 100%;
  border: 1px solid #D9D9D9;
  max-height: 750px;
  overflow-y: auto;
}
.table-title {
  height: 34px;
  line-height: 34px;
  background: #F2F2F2;
  display: flex;
  padding: 0 12px;
}
.table-data {
  height: 40px;
  line-height: 40px;
  background: #fff;
  display: flex;
  padding: 0 12px;
  border-top: 1px solid #D9D9D9;
  position: relative;

  &:last-of-type {
    border-bottom: 1px solid #D9D9D9;
  }
}
.table-operation {
  width: 4%;
  i {
    cursor: pointer;
  }
}
/deep/.block-btn-wrap .el-button {
  width: 100%;
}
.table-title-item, .table-data-item  {
  width: 32%;
  text-align: right;
  font-size: 12px;
  color: #212121;
  &:nth-child(2) {
    text-align: left;
  }
  /deep/.el-input,/deep/ .el-select, .table-text {
    width: 80%;
    height: 40px;
    display: inline-block;
    vertical-align: middle;
  }
  /deep/.el-input__inner {
      height: 32px;
      border-radius: 0;
      border-color: var(--themeColor)
  }
}
.identify-module {
  font-size: 16px;
  line-height: 24px;
  color: #212121;
  margin-bottom: 20px;
}
.image-list {
  margin-top: 30px;
  background: #F5F5F5;
  padding: 20px 0;
  max-height: 750px;
  overflow-y: auto;
  .el-image {
    display: block;
    margin: 0 auto;
  }
  .number {
    font-size: 14px;
    margin-top: 6px;
    text-align: center;
    color: #212121;
    margin-bottom: 20px;
  }
}

.formula-list {
  padding: 20px 0;
  max-height: 750px;
  overflow-y: auto;
}

.formula-item {
  width: 100%;
  padding: 20px;
  background: #F5F5F5;
  margin-bottom: 20px;
  .highlit {
    cursor: pointer;
    &.on {
      background: rgb(227,235,255);
    }
  }
}
.formula-index {
  font-size: 14px;
  color: var(--themeColor);
  margin-bottom: 10px;
  .num {
    display: inline-block;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background: var(--themeColor);
    font-size: 12px;
    line-height: 20px;
    text-align: center;
    color: #FFFFFF;
    margin-right: 4px;
    vertical-align: middle;
  }
}
.formula-content {
  width: 100%;
  padding: 8px 12px;
  border-radius: 2px;
  background: #FFFFFF;
  font-size: 12px;
  line-height: 18px;
  color: #666666;
}
.formula-module-title {
  font-size: 14px;
  line-height: 20px;
  font-weight: 600;
  color: #212121;
  margin-top: 20px;
  margin-bottom: 8px;
}
.formula-calc {
  font-size: 12px;
  line-height: 18px;
  color: #666666;
  margin-bottom: 8px;
}
.formula-error {
  .error {
    font-size: 12px;
    line-height: 18px;
    color: #FB2323;
  }
}
.formula-result {
  .result {
    font-size: 12px;
    line-height: 18px;
    color: #1BA854;
  }
  .error {
    color: #FB2323;
  }
}
.formula-tip {
  font-size: 12px;
  line-height: 20px;
  color: #666666;
  width: 70px;
  display: inline-block;
}
.tabs-box {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}
.search-list {
  display: flex;
}
.search-item {
  width: 76px;
  height: 24px;
  line-height: 24px;
  font-size: 12px;
  text-align: center;
  color: #212121;
  border: 1px solid #D9D9D9;
  cursor: pointer;
  &:first-of-type {
    border-radius: 2px 0px 0px 2px;
  }
  &:last-of-type {
    border-radius: 0px 2px 2px 0px;
  }
  &.active {
    color: var(--themeColor);
    background: #fff;
    border: 1px solid var(--themeColor);
  }
}

.identify-switch {
  font-size: 16px;
  line-height: 24px;
  color: #212121;
  cursor: pointer;
}
.icon-switch {
  background: url(../assets/icon-switch.svg) no-repeat;
  display: inline-block;
  width: 16px;
  height: 16px;
  vertical-align: text-bottom;
  margin-left: 5px;
}
</style>